package com.wj.oauth2.server.controller;

import com.wj.base.result.R;
import com.wj.oauth2.server.util.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("OAuth2Controller")
@RestController
public class OAuth2Controller {

    @RequestMapping("/oAuth2")
    public R oAuth2(@RequestParam("code") String code) throws Exception {
        Map<String, String> body = new HashMap<>();
        body.put("code", code);
        body.put("grant_type","authorization_code");

        Map<String, String> header = new HashMap<>();
        String base64 = Base64.getEncoder().encodeToString("wj-pc:wj-secret".getBytes());
        header.put("Authorization","Basic "+base64);
        HttpResponse response = HttpUtils.doPost("http://localhost:8090", "/auth/oauth/token", "post", header, new HashMap<>(), body);
        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
            String json = EntityUtils.toString(entity);
            return R.ok().addData(json);
        }else{
            return R.err();
        }

    }

    public static void main(String[] args) {
        String s = Base64.getEncoder().encodeToString("wj-pc:wj-secret".getBytes());
        System.out.println(s);//d2otcGM6d2otc2VjcmV0
    }
}
